<?php
/**
 * Простой форум
 *
 * @author tonatos
 */
class c_forum_controller extends c_base_controller {

    public $user_id;

    public $forum_page = 6;

    public $is_admin;
    public $admin_usergroup = "Администраторы форума";
    public $is_user;


    public function __construct() {
        global $modx;        
        parent::__construct();

        $modx->regClientCSS("assets/snippets/mvc/data/forum/style.css");

        $this->user_id = $modx->getLoginUserID();
        if (!empty($this->user_id)){
            $this->is_user = true;            
            $this->is_admin = $modx->isMemberOfWebGroup(array($this->admin_usergroup));
        }else{
            $this->is_user = false;
        }

    }

    public function index(){
        global $modx,$mvc;
        $this->set_modx_field("pagetitle", "Форум");
        $this->set_modx_field("longtitle", "Форум");

        //$this->add_modx_menu("Форум");

        $this->topics = $modx->db->get_records("forum_topic","deleted=0","last_comment desc, createdon desc");

        //Подумать над оптимизацией
        foreach($this->topics as $key=>$topic){

            //Получаем пользователя форума
            try{
                $topic->user = new c_web_users_model($topic->user_id);
            }  catch (Exception $e){
                //Пользователь был удален
                $topic->user = new c_web_users_model(-1);
            }

            //Получаем последнее сообщение
            $comment = $modx->db->get_record("forum_post", "deleted=0 and id_topic=$topic->id", "createdon DESC");
            if ($comment!==false){
                $topic->comment = new c_forum_post_model($comment);
                try{
                    $topic->comment->user = new c_web_users_model($topic->comment->user_id);
                }catch(Exception $e){
                    //Пользователь был удален
                    $topic->comment->user= new c_web_users_model(-1);
                }

            }

            $post_count = $modx->db->get_records("forum_post","deleted=0 and id_topic=$topic->id");
            $topic->post_count = count($post_count);

        }
        
        error_reporting(E_ALL);
        $modx->regClientCSS("assets/snippets/mvc/data/form/style.css");
        $this->show("index");
    }

    public function delete_topic($params){

        //Отправляем на вход на сайт
        if (!$this->is_user){
            $cabinet = new c_workplace_controller();
        }

        $id = (int)$params[2];
        if (!empty($id) && $this->is_admin){
            $model = new c_forum_topic_model($id);
            $model->deleted = time();
            $model->save();
        }
        $this->redirect($this->forum_page);
    }

    public function edit_topic($params){
        global $mvc;


        //Отправляем на вход на сайт
        if (!$this->is_user){
            //Создаем контроллер личного кабинета,
            //он сам отправит пользователя логинится
            $cabinet = new c_workplace_controller();
        }

        $id = (int)$params[2];

        if ((!$this->is_admin)&&(!empty($id))){
            $this->redirect($this->forum_page);
        }

        $this->set_modx_field("pagetitle", "Изменить тему");

        //$this->add_modx_menu("Форум",$this->forum_page);
        $this->add_modx_menu("Новая тема");

        $this->form = new c_form_controller();
        $this->form->add_antispam();
        $this->form->add_hidden("id");
        $this->form->add_varchar("name", "Название темы","",1);

        if (empty($id)){
            $this->form->add_text("message","Сообщение","",1);
        }

        if ($this->form->data_submitted()) {
            if ($this->form->is_validate()) {

                $data = $this->form->get_data();

                if (empty($id)){
                    $message = $data['message'];
                    unset($data['message']);
                }

                $model = new c_forum_topic_model($data);
                $model->save();

                if (empty($id)){
                    $post = new c_forum_post_model();
                    $post->id_topic = $model->id;
                    $post->message = $message;
                    $post->save();

                    //Ставим в очередь на рассылку
                    $this->notify_subscribers($post);

                    //Сразу уведомляем админов
                    $this->notify_admins($model,$post);

                }
                $this->redirect($this->forum_page);

            }
        }else{
            if (!empty($id)){
                $model = new c_forum_topic_model($id);
                $this->form->set_data($model);
            }
        }

        $this->form->show_form();

    }


    /**
     *
     * @global <type> $modx
     * @global c_mvc_util $mvc
     * @param <type> $params
     */
    public function topic($params){
        global $modx,$mvc;
        $id = (int)$params[2];

        if (empty($id)) {
            $this->redirect($this->forum_page);
        }

        $this->topic = new c_forum_topic_model($id);

        if ($this->topic->deleted!=0){
            $mvc->send_error_page();
        }

        $this->set_modx_field("pagetitle", htmlspecialchars($this->topic->name));

        //$this->add_modx_menu("Форум",$this->forum_page);
        $this->add_modx_menu(htmlspecialchars($this->topic->name));

        $form = new c_form_controller();
        $form->add_antispam();
        $form->add_text("message","Комментарий","",1);
        $form->action = "forum/topic/".$this->topic->id."#last";


        //Только аторизованные пользователи могут оставлять сообщения
        if ($this->is_user){

            if ($form->data_submitted()) {
                if ($form->is_validate()) {
                    $data = $form->get_data();

                    $model = new c_forum_post_model($data);
                    $model->id_topic = $this->topic->id;
                    $model->save();

                    $this->topic->last_comment=time();
                    $this->topic->save();

                    $this->notify_subscribers($model);

                    $this->notify_admins($this->topic,$model);

                    $this->redirect("/".$form->action);
                }
            }
        }

        //Показываем удаленные записи 15 минут после удаления
        $del_min = time() - 60*15;

        $posts = $modx->db->get_records("forum_post","(deleted=0 or deleted>$del_min) and id_topic = $id","createdon");

        $this->topic->post_count = count($posts);
        $user_ids = array();

        foreach($posts as $post){
            $user_ids[$post->user_id] = $post->user_id;
        }

        $users = array();
        foreach($user_ids as $user_id){
            $users[$user_id] = new c_web_users_model($user_id);
        }

        foreach ($posts as $post) {
            $post->user = $users[$post->user_id];
        }

        $this->posts = $posts;
        $this->form = $form;
        
        $this->show("topic");
    }


    public function delete_post($params){
        $id = (int)$params[2];

        //Отправляем на вход на сайт
        if (!$this->is_user){
            $cabinet = new c_workplace_controller();
        }


        if (!empty($id) && $this->is_admin){
            $model = new c_forum_post_model($id);
            $model->deleted = time();
            $model->save();            
            $this->redirect("/forum/topic/$model->id_topic#post_$id");
        }
        $this->redirect($this->forum_page);
    }

    public function edit_post($params){
        
        $id = (int)$params[2];

        if (empty($id)){
            $this->redirect($this->forum_page);
        }

        //Отправляем на вход на сайт
        if (!$this->is_user){
            $cabinet = new c_workplace_controller();
        }

        $post = new c_forum_post_model($id);



        if (!$this->is_admin){
            $this->redirect("/forum/topic/$post->id_topic");
        }

        $this->set_modx_field("pagetitle", "Изменить сообщение");

        //$this->add_modx_menu("Форум",$this->forum_page);
        $this->add_modx_menu("Изменить сообщение");



        $form = new c_form_controller();
        $form->add_antispam();
        $form->add_text("message","Комментарий","",1);

        $form->add_cancel("/forum/topic/$post->id_topic#post_$post->id");
        


        if ($form->data_submitted()) {
            if ($form->is_validate()) {
                $data = $form->get_data();

                $model = new c_forum_post_model($id);
                $model->message = $data['message'];
                $model->save();
                $this->redirect("/forum/topic/$post->id_topic#post_$post->id");

            }
        }else{
            $model = new c_forum_post_model($id);
            $form->set_data($model);
        }

        $form->show_form();
    }


    public function restore_post($params){
        $id = (int)$params[2];

        //Отправляем на вход на сайт
        if (!$this->is_user){
            $cabinet = new c_workplace_controller();
        }

        if (!empty($id) && $this->is_admin){
            $model = new c_forum_post_model($id);
            $model->deleted = 0;
            $model->save();
            $this->redirect("/forum/topic/$model->id_topic#post_$id");
        }
        $this->redirect($this->forum_page);

    }

    /**
     * Преобразование в html сущности, перевод строки в br
     * и автогенерация ссылок
     *
     * @param string $str
     * @return string
     */
    public function auto_convert($str){
        $in=array(
            '`((?:https?|ftp)://\S+[[:alnum:]]/?)`si',
            '`((?<!//)(www\.\S+[[:alnum:]]/?))`si',
            "#((?<!//))([a-z0-9\-_.]+?)@([\w\-]+\.([\w\-\.]+\.)*[\w]+)#i"
        );
        $out=array(
            '<a href="$1" target="_blank">$1</a> ',
            '<a href="http://$1" target="_blank">$1</a>',
            "\\1<a href=\"mailto:\\2@\\3\" class=orange>\\2@\\3</a>"
        );
        return nl2br(preg_replace($in,$out,htmlspecialchars($str)));
    }


    public function wrap($str){

        if (mb_strlen($str)>250){
            $arrs = explode(" ",$str);
            $result = "";
            foreach($arrs as $word){
                $result.=$word." ";
                if (mb_strlen($result)>180){
                    return $result." ...";
                }
            }
        }
        return $str;
    }

    public function import_from_vanilla(){
        global $modx;

        return;

        echo "<pre>";
        /* очищаем */
        //$modx->db->query("truncate table trfa_forum_topic");
        //$modx->db->query("truncate table trfa_forum_post");

        $topics = $modx->db->get_records("select
            DiscussionId as id,
            name,
            UNIX_TIMESTAMP( `DateCreated`) AS createdon,
            `AuthUserID` AS user_id,
            UNIX_TIMESTAMP( `DateLastActive`) AS last_comment,
            `Active` as deleted from lum_Discussion order by DiscussionId");


//        $topics2 = $modx->db->get_records("select * from lum_Discussion");

        foreach($topics as $topic){
            $topic->deleted = empty($topic->deleted)?1:0;
            $modx->db->insert((array)$topic,"trfa_forum_topic");

            $comments = $modx->db->get_records("select CommentID as id, DiscussionID as id_topic, AuthUserID as user_id, UNIX_TIMESTAMP(DateCreated) as createdon, Body as message, deleted from  lum_Comment where DiscussionID=$topic->id");
            foreach($comments as $row){
                $row->message = $modx->db->escape($row->message);

                $modx->db->insert((array)$row, "trfa_forum_post");
            }

        }


        //print_r($topics);

    }

    protected function notify_admins($topic,$post){
        global $modx;

        //Ищем администраторов форума
        $admins = $modx->db->get_records(
                "select webuser from ".$modx->getFullTableName("webgroup_names")." wm,".
                $modx->getFullTableName("web_groups")." wg where wm.id=wg.webgroup and wm.name like '$this->admin_usergroup' ");

        //Отправляем письмо с уведомлением администратору форума
        foreach($admins as $admin_id){
            $admin = new c_web_users_model($admin_id->webuser);
            $this->template->admin = $admin;
            $this->template->message = $post->message;
            $this->template->topic = $topic;
            $this->template->link_look=$modx->config['site_url']."forum/topic/$topic->id#post_$post->id";
            $this->template->link_update=$modx->config['site_url']."forum/edit_post/$post->id";
            $this->template->link_delete=$modx->config['site_url']."forum/delete_post/$post->id";
            $this->template->user = new c_web_users_model($this->user_id);
            $this->send_mail_from_template($admin->email, "Новый комментарий на форуме сайта", "mail_notify");
        }
        
    }

    protected function notify_subscribers($post){
        $raw = new c_site_mailer_raw_model();
        $raw->param_id = $post->id;
        $raw->param_action = "new_post";
        $raw->controller = "forum";
        $raw->save();
    }

    protected function cron(){
        global $modx;
        $raws = $modx->db->get_records("select r.*, p.id_topic, p.message, p.user_id, p.deleted from ".$modx->getFullTableName("site_mailer_raw")." r, ".
                $modx->getFullTableName("forum_post")." p where p.id=r.param_id and r.controller='forum' and p.deleted=0 order by r.createdon");

        $user_ids = array();
        $topic_ids = array();

        foreach($raws as $post){
            if ($post->deleted==0){
                $user_ids[$post->user_id] = $post->user_id;
                $topic_ids[$post->id_topic] = $post->id_topic;
            }
        }

        if (empty($topic_ids)) return false;

        $users = array();
        foreach($user_ids as $user_id){
            try{
                $users[$user_id] = new c_web_users_model($user_id);
            }catch(Exceprion $e){
                $users[$user_id] = new c_web_users_model(-1);
            }
        }

        $topics = $modx->db->records_synh_id($modx->db->get_records("forum_topic","id in (".implode(",",$topic_ids).")"));

        

        foreach ($raws as $post) {
            $post->user = $users[$post->user_id];
            if (!isset($topics[$post->id_topic]->posts)){
                $topics[$post->id_topic]->posts=array();
            }
            $topics[$post->id_topic]->posts[] = $post;
        }

        $this->topics = $topics;

        $modx->db->delete($modx->getFullTableName("site_mailer_raw"),"controller='forum'");

        return $this->show("cron",true);
    }
}
?>
